﻿using System;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Ganss.XSS;
using IceCS.Utility;
using Newtonsoft.Json;

namespace IceCS.Cmd
{
    class Program
    {
        static void Main(string[] args)
        {
            MainAsync();
            while (true)
            {
                Task.Delay(1000).Wait();
            }
        }

        static async void MainAsync()
        {
            Console.WriteLine($"Method:{nameof(MainAsync)},Task Id:{Task.CurrentId},Thread Id:{Thread.CurrentThread.ManagedThreadId}");
            int i = 0;
            Task[] tasks = new Task[200];
            while (i < 200)
            {
                tasks[i] = new Task(() =>
                  {
                      CounterAdd();
                      CounterAddLock();
                      CounterAddMonitorLock();
                  });
                tasks[i].Start();
                i++;
            }
            await Task.WhenAll(tasks).ContinueWith((task) =>
            {
                Console.WriteLine($"执行200次完毕,Counter :{Counter},CounterLock:{CounterLock} {CounterLock2},CounterMonitorLock:{CounterMonitorLock} {CounterMonitorLock2}");
            });
        }
        static int Counter = 0;
        static int CounterLock = 0;
        static int CounterMonitorLock = 0;
        static int CounterLock2 = 0;
        static int CounterMonitorLock2 = 0;
        static object lockObj = new object();
        static object lockObj2 = new object();

        /// <summary>
        /// 不加锁，随机加，值可能被覆盖
        /// </summary>
        static async void CounterAdd()
        {
            Counter++;
            //Console.WriteLine($"Thread {Thread.CurrentThread.ManagedThreadId} Task {Task.CurrentId} change counter {Counter}");
        }

        /// <summary>
        /// 加锁，无序变有序，lock语法糖形式
        /// </summary>
        static async void CounterAddLock()
        {
            CounterLock2++;
            lock (lockObj)
            {
                CounterLock++;
                //Console.WriteLine($"Lock Thread {Thread.CurrentThread.ManagedThreadId} Task {Task.CurrentId} change counter {CounterLock}");
            }
            CounterLock2++;
            var text = "123A";
            ConsoleHelper.Bee();
        }

        /// <summary>
        /// 加锁，无序变有序,monitor形式
        /// </summary>
        static async void CounterAddMonitorLock()
        {
            CounterMonitorLock2++;
            Monitor.Enter(lockObj2);
            {
                CounterMonitorLock++;
                //Console.WriteLine($"Monitor Lock Thread {Thread.CurrentThread.ManagedThreadId} Task {Task.CurrentId} change counter {CounterMonitorLock}");
            }
            Monitor.Exit(lockObj2);
            CounterMonitorLock2++;
        }
    }
}